<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/16
 * Time: 15:50
 */

namespace App\Http\Classes;

use Illuminate\Support\Facades\DB;

class Help
{
    private $tableName = 'about';
    private $tableDB = null;
    private $error = 0;
    private $message = array(
        0 => '无匹配的数据',
        1 => '修改失败'
    );

    public function __construct( $id = null )
    {
        $this->tableDB = DB::table( $this->tableName );

        if ( $id !== null )
        {
            if ( $id === 'aboutUs' )
            {
                $this->tableDB = $this->tableDB->where('type', '=', '关于我们');
            }
            else if ( $id === 'customerService' )
            {
                $this->tableDB = $this->tableDB->where('type', '=', '客户服务');
            }
            else if ( $id === 'help')
            {
                $this->tableDB = $this->tableDB->where('type', '=', '帮助');
            }
        }
    }

    public function getAboutUs()
    {
        $result = $this->getByType('关于我们');
        return $result ? $result : null;
    }

    public function getCustomerService()
    {
        $result = $this->getByType('客户服务');
        return $result ? $result : null;
    }

    public function getHelp()
    {
        $result = $this->getByType('帮助');
        return $result ? $result : null;
    }

    private function getByType($type)
    {
        $result = $this->tableDB;

        $result = $result->where('type', '=', $type)->get();

        if ( $result )
        {
            return $result[0];
        }
        else
        {
            $this->error = 0;
            return null;
        }
    }

    public function updateAboutUs($content)
    {
        $result = $this->updateByType('关于我们', $content);
        return $result;
    }

    public function updateHelp($content)
    {
        $result = $this->updateByType('帮助', $content);
        return $result;
    }

    public function updateCustomerService($content)
    {
        $result = $this->updateByType('客户服务', $content);
        return $result;
    }

    private function updateByType($type, $content)
    {
        $result = $this->tableDB;

        $result = $result->where('type', '=', $type)->update([
            'content' => $content,
            'update_time' => date('Y-m-d h:i:s')
        ]);

        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 1;
            return false;
        }
    }

    public function getMessage()
    {
        return $this->message[ $this->error ];
    }
}